package xin.vsftpd.job;

import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import xin.vsftpd.Config.Env;
import xin.vsftpd.model.TransLogInfo;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <pre>
 * vsftpd 日志任务
 * </pre>
 *
 * @author lixin_ma@outlook.com
 * @version 1.0
 * @since 2019/7/9
 */
@Slf4j
public class VsftpdJob implements Job {
	
	
	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		String date = new SimpleDateFormat("yyyyMMdd").format(new Date(System.currentTimeMillis()));
		String path = (String) Env.get("log");
		
		/* 正常文件存储为 “/var/log/vsftpd/vsftpd.log” 时，其切割后文件为“/var/log/vsftpd/vsftpd.log-${yyyyMMdd}” */
		String file = path + "-" + date;
		doParse(file);
	}
	
	/**
	 * 解析传输日志
	 * @param file 文件名称
	 * @return
	 */
	public List<TransLogInfo>  doParse(String file){
		log.info("vsftp 传输日志解析 ，文件：{}",file);
		List<TransLogInfo> result = new ArrayList<>();
		BufferedReader in = null;
		try {
			in = new BufferedReader(new FileReader(file));
			String line;
			while((line=in.readLine())!=null){
				line = repaceWhiteSapce(line);
				String[] info = line.split(" ");
				result.add(TransLogInfo.builder()
						.transDate(new Date(info[0] + " " + info[1] + " " + info[2] + " " + info[3] + " " + info[4]))
						.cost(info[5])
						.clientIp(info[6])
						.fileSize(info[7])
						.fileName(info[8])
						.type(info[9])
						.operate(info[10])
						.direction(info[11])
						.mode(info[12])
						.username(info[13])
						.service(info[14])
						.auth(info[15])
						.uid(info[16])
						.state(info[17])
						.build());
			}
			
			/**
			 * TODO 数据入库 或 调用服务将解析结果返回
			 */
		} catch (IOException e) {
			log.error("fpt传输日志解析失败！",e);
		}finally {
			if(in != null){
				try{in.close();}catch (IOException e) {e.printStackTrace();}
			}
		}
		return result;
	}
	
	/**
	 * 去除多余空格
	 * @param original
	 * @return
	 */
	public static String repaceWhiteSapce(String original){
		String regEx = "\\s+";
		if(original != null ){
			return original.replaceAll(regEx," ");
		}else{
			throw new IllegalArgumentException("original str can not be null");
		}
	}
}
